package Model
{
	import Model.Topic;
	import Model.Topics;
	
	import mx.collections.ArrayCollection;

	[Bindable]
	public class Posts
	{
		public static var _instance:Posts;
		private var _all:ArrayCollection;
		private var _selectedIndices:Array;
		
		public function Posts()
		{
			if(_instance != null)
			{
				throw new Error("Posts cannot be instanciated. You can only use it's properties");
			}
			_instance = this;
		}
		
		public static function get instance():Posts
		{
			if(_instance == null) 
			{
				_instance = new Posts();
			}
			return _instance;
		}
		
		public function get all():ArrayCollection
		{
			return _all;
		}
		
		public function set all(posts:ArrayCollection):void
		{
			_all = new ArrayCollection(posts.source);
		}
		
		public function set selectedIndices(indices:Array):void
		{
			_selectedIndices = indices;
		}
		
		public function selected():ArrayCollection
		{
			var selectedPosts:ArrayCollection = new ArrayCollection();
			var i:Number;
			for(i = 0; i < _selectedIndices.length; i++)
			{
				var index:Number = _selectedIndices[i];
				selectedPosts.addItem(_all[index]);
			}
			return selectedPosts;
		}
		
		public function selectedIds():Array
		{
			var selectedIds:Array = new Array();
			var i:Number;
			for(i = 0; i < selected().length; i++)
			{
				var id:Number = selected()[i].ID;
				selectedIds.push(id);
			}
			return selectedIds;
		}
		
		public function getSelectedTopicsPosts():ArrayCollection
		{
			var topics:ArrayCollection = Topics.instance.getSelectedTopics();
			if(topics.length == 0)
				return new ArrayCollection();
			
			var Posts0:Array = topics[0].TopicPosts;
			for(var i:int = 1; i < topics.length; i++)
			{
				var Posts1:Array =topics[i].TopicPosts;
				Posts0 = Posts0.concat(Posts1);
				
			}
			Posts0.sort(Array.NUMERIC);
			
			var selectedTopicsPosts:ArrayCollection =  new ArrayCollection();
			for(var j:int = 0; j < Posts0.length; j++)
			{
				var k:int = Posts0[j];
				var post:Post = _all[k];
				selectedTopicsPosts.addItem(post);
			}
			return selectedTopicsPosts;
		}
		
		public function getFontColor(post:Post):uint
		{
			var topic1:Topic = Topics.instance.current();
			if (post.topic == topic1) 
				return 0;
			else return 10921638;
		}
		
		public function getBackgroundColor(post:Post):uint
		{
			if (selectedIds().indexOf(post.ID)==-1) 
				return 16777215;
			else return  14741216;
		}
		
	}
}